package com.phospherus.common.service.impl;

import com.phospherus.common.SerialNumber;
import com.phospherus.common.repository.SerialNumberRepository;
import com.phospherus.common.service.ISerialNumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * @author songjinlong
 * @version 1.0
 * @since 2018/1/5
 */
@Service
public class SerialNumberService implements ISerialNumberService {
    @Autowired
    private SerialNumberRepository repository;

    @Override
    @Transactional
    public synchronized int getNextNum(String year) {
        SerialNumber serialNumber = repository.findByYear(year);
        if (serialNumber == null) {
            serialNumber = new SerialNumber();
            serialNumber.setYear(year);
            serialNumber.setCurrNum(1);
            repository.save(serialNumber);
        }
        int currNum = serialNumber.getCurrNum();
        serialNumber.setCurrNum(currNum + 1);
        return currNum;
    }
}
